package com.cardone.platform.common.dao;

import java.util.Map;
import java.util.UUID;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.collections.MapUtils;

import com.cardone.context.Attributes;
import com.cardone.context.ContextHolder;
import com.cardone.context.DictionaryException;
import com.cardone.context.function.Execution1Function;
import com.cardone.persistent.support.JdbcTemplateSupport;
import com.google.common.collect.Maps;

/**
 * 实体编号
 *
 * @author yaohaitao
 *
 */
@Getter
@Setter
public class EntityCodeJdbcDao implements EntityCodeDao {
	@Override
	public String generateCode(final String id, final String typeCode, final Execution1Function<String, String> function, final Map<String, Object> parameters) {
		final String insertByNotExistsCodeSql = SqlIds.insertByNotExistsCodeFor.id() + id;

		final String readMaxCodeByCodeSql = SqlIds.readMaxCodeByCodeFor.id() + id;

		final Map<String, Object> newParameters = Maps.newHashMap();

		if (MapUtils.isNotEmpty(parameters)) {
			newParameters.putAll(parameters);
		}

		newParameters.put(Attributes.typeCode.name(), typeCode);

		String code = null;

		int reCount = 0;

		while (true) {
			code = ContextHolder.getBean(JdbcTemplateSupport.class).read(String.class, readMaxCodeByCodeSql, newParameters);

			newParameters.put(Attributes.id.name(), UUID.randomUUID().toString());
			newParameters.put(Attributes.code.name(), code);
			newParameters.put(Attributes.typeCode.name(), typeCode);

			if (function != null) {
				code = function.execution(code);
			}

			final int insertCount = ContextHolder.getBean(JdbcTemplateSupport.class).update(insertByNotExistsCodeSql, newParameters);

			if (insertCount > 0) {
				break;
			}

			reCount++;

			if (reCount > 100) {
				throw new DictionaryException("重试了100次也没有获取到不重复的编号");
			}
		}

		return code;
	}

}